package com.cnofd.demo.util;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;


//import org.apache.sanselan.ImageInfo;
//import org.apache.sanselan.ImageReadException;
//import org.apache.sanselan.Sanselan;
import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;


/**
 * @ClassName: ImageUtil
 * @Description: 图片工具类
 * @author cnofd
 * @date   2022年1月22日
 */
public class ImageUtil {

    /**
     * 获取图片信息
     * @param file
     * @return
     */
    public static float[] getImageInfo(File file) {
        //返回数据
        float[] axis = {0, 0};
        try {
            //ImageInfo imageInfo = Sanselan.getImageInfo(file);
            ImageInfo imageInfo = Imaging.getImageInfo(file);
            if(null != imageInfo) {
                Integer widthPx = imageInfo.getWidth();
                Integer heightPx = imageInfo.getHeight();
                Integer widthDpi = imageInfo.getPhysicalWidthDpi();
                Integer heightDpi = imageInfo.getPhysicalHeightDpi();
                DecimalFormat df = new DecimalFormat("0.##");
                Double widthMm = 1d;
                Double heightMm = 1d;
                
                //如果得不到DPI值，则按照120DPI换算
                widthDpi = -1 != widthDpi ? widthDpi : 120;
                heightDpi = -1 != heightDpi ? widthDpi : 120;
                if(-1 != widthDpi && -1 != heightDpi) {
                    try {
                        widthMm = Double.valueOf(widthPx) / widthDpi * 25.4;
                        heightMm = Double.valueOf(heightPx) / heightDpi * 25.4;
                    } catch (NumberFormatException e) {
                        System.out.println(e.getMessage());
                    }
                }
                //分别计算dpi的值
                String widthMmStr = df.format(widthMm);
                String heightMmStr = df.format(heightMm);
                
                axis[0] = Float.valueOf(widthMmStr);
                axis[1] = Float.valueOf(heightMmStr);
            }
        } catch (ImageReadException e) {
            System.out.println(e.getMessage());
            return axis;
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return axis;
        }

        return axis;
    }    
}